package com.coursehub.course.transaction;

import com.coursehub.shared.client.ServiceClient;
import com.coursehub.shared.transaction.AbstractTransactionStep;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 初始化收藏题库和错题库的事务步骤
 * 在学生成功加入课程后，自动为学生创建收藏题库和错题库
 */
@Slf4j
@Component
public class InitializeQuestionBanksStep extends AbstractTransactionStep {
    
    @Autowired
    private ServiceClient serviceClient;
    
    // 用于补偿操作的题库ID
    private String favoriteQuestionBankId;
    private String wrongQuestionBankId;
    private String studentId;
    private String courseId;
    private String authorizationHeader;
    private String userIdHeader;
    private String userAccountHeader;
    
    public InitializeQuestionBanksStep() {
        super("初始化题库", "为学生初始化收藏题库和错题库");
    }
    
    public void setParameters(String studentId, String courseId, String authorizationHeader, String userIdHeader, String userAccountHeader) {
        this.studentId = studentId;
        this.courseId = courseId;
        this.authorizationHeader = authorizationHeader;
        this.userIdHeader = userIdHeader;
        this.userAccountHeader = userAccountHeader;
    }
    
    @Override
    protected void doExecute() throws Exception {
        log.info("开始初始化学生 {} 在课程 {} 的收藏题库和错题库", studentId, courseId);
        
        try {
            // 生成收藏题库ID
            favoriteQuestionBankId = UUID.randomUUID().toString();
            
            // 创建收藏题库请求数据
            Map<String, Object> favoriteRequest = new HashMap<>();
            favoriteRequest.put("favoriteQuestionBankId", favoriteQuestionBankId);
            favoriteRequest.put("userId", studentId);
            favoriteRequest.put("courseId", courseId);
            
            log.debug("创建收藏题库请求: {}", favoriteRequest);
            
            // 调用exercise-management服务创建收藏题库
            if (authorizationHeader != null) {
                // 设置所有头信息
                Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", authorizationHeader);
                if (userIdHeader != null) {
                    headers.put("X-User-Id", userIdHeader);
                }
                if (userAccountHeader != null) {
                    headers.put("X-User-Account", userAccountHeader);
                }
                serviceClient.post("exercise-management", "/api/exercises/favorite-banks", favoriteRequest, Object.class, headers);
                log.info("使用完整头信息调用exercise-management服务创建收藏题库: Authorization={}, X-User-Id={}, X-User-Account={}", 
                        "Bearer ***", userIdHeader, userAccountHeader);
            } else {
                serviceClient.post("exercise-management", "/api/exercises/favorite-banks", favoriteRequest, Object.class);
                log.warn("未找到Authorization头，直接调用exercise-management服务创建收藏题库");
            }
            log.info("收藏题库创建成功: favoriteQuestionBankId={}", favoriteQuestionBankId);
            
            // 生成错题库ID
            wrongQuestionBankId = UUID.randomUUID().toString();
            
            // 创建错题库请求数据
            Map<String, Object> wrongRequest = new HashMap<>();
            wrongRequest.put("wrongQuestionBankId", wrongQuestionBankId);
            wrongRequest.put("userId", studentId);
            wrongRequest.put("courseId", courseId);
            
            log.debug("创建错题库请求: {}", wrongRequest);
            
            // 调用exercise-management服务创建错题库
            if (authorizationHeader != null) {
                // 设置所有头信息
                Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", authorizationHeader);
                if (userIdHeader != null) {
                    headers.put("X-User-Id", userIdHeader);
                }
                if (userAccountHeader != null) {
                    headers.put("X-User-Account", userAccountHeader);
                }
                serviceClient.post("exercise-management", "/api/exercises/wrong-banks", wrongRequest, Object.class, headers);
                log.info("使用完整头信息调用exercise-management服务创建错题库: Authorization={}, X-User-Id={}, X-User-Account={}", 
                        "Bearer ***", userIdHeader, userAccountHeader);
            } else {
                serviceClient.post("exercise-management", "/api/exercises/wrong-banks", wrongRequest, Object.class);
                log.warn("未找到Authorization头，直接调用exercise-management服务创建错题库");
            }
            log.info("错题库创建成功: wrongQuestionBankId={}", wrongQuestionBankId);
            
            log.info("学生 {} 在课程 {} 的题库初始化完成", studentId, courseId);
            
        } catch (Exception e) {
            log.error("初始化题库失败: studentId={}, courseId={}, error={}", studentId, courseId, e.getMessage(), e);
            throw new Exception("初始化题库失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    protected void doCompensate() throws Exception {
        log.info("开始补偿学生 {} 在课程 {} 的题库初始化", studentId, courseId);
        
        // 删除收藏题库
        if (favoriteQuestionBankId != null) {
            try {
                serviceClient.delete("exercise-management", "/api/exercises/favorite-banks/" + favoriteQuestionBankId, Object.class);
                log.info("收藏题库删除成功: favoriteQuestionBankId={}", favoriteQuestionBankId);
            } catch (Exception e) {
                log.warn("收藏题库删除失败: favoriteQuestionBankId={}, error={}", favoriteQuestionBankId, e.getMessage());
            }
        }
        
        // 删除错题库
        if (wrongQuestionBankId != null) {
            try {
                serviceClient.delete("exercise-management", "/api/exercises/wrong-banks/" + wrongQuestionBankId, Object.class);
                log.info("错题库删除成功: wrongQuestionBankId={}", wrongQuestionBankId);
            } catch (Exception e) {
                log.warn("错题库删除失败: wrongQuestionBankId={}, error={}", wrongQuestionBankId, e.getMessage());
            }
        }
        
        log.info("学生 {} 在课程 {} 的题库初始化补偿完成", studentId, courseId);
    }
}